package com.example.petstore.controller;

import com.example.petstore.common.CommonResponse;
import com.example.petstore.domain.Admin;
import com.example.petstore.domain.Item;
import com.example.petstore.domain.Order;
import com.example.petstore.domain.User;
import com.example.petstore.service.*;
import com.example.petstore.util.CryptoUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;


import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@Controller
@SessionAttributes({"loginAdmin", "verifyCode"})
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private LineItemService lineItemService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private UserService userService;
    @Autowired
    private CodeService codeService;
    @Autowired
    private UserInfoService userInfoService;

    private  final ObjectMapper objectMapper=new ObjectMapper();
    @GetMapping("/sendPhoneCodeForAdminLogin")/*test ok*/
    @ResponseBody
    public CommonResponse sendPhoneCodeForAdminLogin(String phoneNumber){
        return codeService.sendPhoneCodeForAdmin(phoneNumber, "login");
    }
    @GetMapping("/sendPhoneCodeForAdminRegister")/*test ok*/
    @ResponseBody
    public CommonResponse sendPhoneCodeForAdminRegister(String phoneNumber){
        return codeService.sendPhoneCodeForAdmin(phoneNumber, "register");
    }

    @GetMapping("/registerForm")
    public String registerForm() {
        return "seller_register";
    }
    @PostMapping("/register")/*test ok*/
    public String Register(@RequestParam("username") String username,@RequestParam("password") String password,@RequestParam("phoneNumber") String phoneNumber,@RequestParam("phoneCode") String phoneCode,@RequestParam("inviteCode") String inviteCode,Model model) {
      int status1 = codeService.checkPhoneCodeForAdminRegister(phoneNumber,phoneCode).getStatus();
      int status2 = codeService.verifyInviteCode(inviteCode).getStatus();
      if(status1 != 1){
          String msg = codeService.checkPhoneCodeForAdminRegister(phoneNumber,phoneCode).getMessage();
          model.addAttribute("errorMsg",msg);
          return "seller_register";
      } else if (status2 != 1) {
          String msg = codeService.verifyInviteCode(inviteCode).getMessage();
          model.addAttribute("errorMsg",msg);
          return "seller_register";
      }else {
          Admin admin = new Admin();
          admin.setAdminname(username);
          admin.setPassword(CryptoUtil.SHA256(password));
          admin.setPhoneNumber(phoneNumber);
          adminService.createAdmin(admin);
          model.addAttribute("loginAdmin",admin);
          return "redirect:http://localhost:8081/admin/showData";
      }

    }
//    @PostMapping("/loginByName")
//    public String loginByName(@RequestParam("username") String username, @RequestParam("password") String password,@RequestParam("code") String code, Model model) {
//        Admin admin = adminService.findByUsernameAndPassword(username,password);
//        String verifyCode = (String) model.getAttribute("verifyCode");
//        if(!verifyCode.equals(code)){
//            model.addAttribute("errorMsg", "验证码错误！");
//            return "help";
//        }
//        else if(admin != null) {
//            model.addAttribute("loginAdmin",admin);
//            return "seller_showdata";
//
//        }
//        else {
//            return "help";
//        }
//
//
//    }
@PostMapping ("/loginByName")
public String loginByName(@RequestParam("username") String username, @RequestParam("password") String password,@RequestParam("code") String code, Model model) {
        Admin admin = adminService.findByUsernameAndPassword(username,password);//CryptoUtil.SHA256(password)   xxxxxxxxxx.SHA256(password)
        String verifyCode = (String) model.getAttribute("verifyCode");
        System.out.println(code);
        System.out.println(verifyCode);

    System.out.println("name="+username+"  password="+password);

//    if(verifyCode==null){
//        System.out.println("test");
//        return "redirect:http://localhost:8081/admin/login";
//    }

//    if(!verifyCode.equals(code)){
//        model.addAttribute("errorMsg", "验证码错误！");
//
////            回到登录页面
//        return "redirect:http://localhost:8081/admin/login";
//    }else{
        if(admin != null) {
            model.addAttribute("loginAdmin",admin);
            return "redirect:http://localhost:8081/admin/showData";

        }
        else {
            System.out.println("false");
            model.addAttribute("errorMsg","密码错误！");
            return "seller_loginbyname";

        }
   // }

}
    @PostMapping("/loginByPhone")/*test ok*/
    public String loginByPhone(@RequestParam("phoneNumber") String phoneNumber,@RequestParam("phoneCode") String phoneCode,Model model) {
        System.out.println("1111");
        System.out.println(phoneCode);
        System.out.println(phoneNumber);
        if(adminService.findByPhoneNumber(phoneNumber) == null) {
            model.addAttribute("errorMsg","该手机号未注册！");
            return "seller_loginbyphone";//"登陆界面/不跳转";
        }
        else if(codeService.checkPhoneCodeForAdminLogin(phoneNumber,phoneCode).getStatus() == 1){

            Admin admin = adminService.findByPhoneNumber(phoneNumber);
            model.addAttribute("loginAdmin",admin);
            System.out.println(admin);
            return "redirect:http://localhost:8081/admin/showData";//"admin登录主界面"
        }
        else{
            System.out.println(codeService.checkPhoneCodeForAdminLogin(phoneNumber,phoneCode).getStatus());
            return "seller_loginbyphone";//"登陆界面/不跳转"
             }
    }

    @GetMapping("/message")
    public String ToMessage(Model model,@ModelAttribute("loginAdmin") Admin admin){
        List<String> useridList= messageService.getDistinctUserIDsAndUsernamesOrderByDateDesc();
        System.out.println(useridList);
        Map<String, Integer> userList = new HashMap<>(); // 用于存储 userId 和 count 的映射关系
        for (String userId : useridList) {
            int count = messageService.countMessagesForAdmin(userId,admin.getAdminname());
            userList.put(userId, count);
        }

//可以通过 userId 直接获取对应的 count
        System.out.println(userList);

        model.addAttribute("userList",userList);
        System.out.println();

        return "seller_cs";
    }
    @GetMapping("/chat")
    public String ToChat(){
        return "seller_cs";
    }



    @GetMapping("/showData")/*test ok*/
    public String DataController( Model model) {
        List<Order> allOrders = orderService.getAllOrders();
        //List<Order> MonthOrders = orderService.findByYearAndMonth(year,month);
        Map<String, Double> monthIncomeMap = calculateIncomeByYearMonth();
        double totalIncome = getOrderTotalPrice(orderService.getOrdersByStatus(1,0,0,0,0).getData());
        double totalOutcome = getOrderTotalPrice(orderService.getOrdersByStatus(1,0,0,1,0).getData());
        List<Map.Entry<String, Integer>> itemListBySale = lineItemService.calculateTotalQuantityAndSort();
        List<Item> itemListByView = itemService.getItemsOrderedByViewsDesc();
        int viewsNumber = itemService.sumViews();
        model.addAttribute("monthIncomeMap",monthIncomeMap);
        model.addAttribute("totalIncome",totalIncome);
        model.addAttribute("totalOutcome",totalOutcome);
        model.addAttribute("orderNumber",allOrders.size());
        model.addAttribute("itemListBySale",itemListBySale);
        model.addAttribute("itemListByView",itemListByView);
        model.addAttribute("viewsNumber",viewsNumber);

        System.out.println(monthIncomeMap);

        return "seller_showdata";//test

    }
//    @GetMapping("/items")
//    public String itemManager(Model model){
//        model.addAttribute("itemList",itemService.getItemList1());
//        return "商品管理界面";
//    }
    @GetMapping("/add")/*test ok*/
    public String addItem(Model model) {
//        model.addAttribute("productIdList",productService.getProductIdList());
//        System.out.println(productService.getProductIdList());
        System.out.println("saasd");
        return "seller_add";//商品添加界面
    }
//    @GetMapping("/products")/*test ok*/
//    public String productManager(Model model) {
//        model.addAttribute("categoryList",categoryService.getCategoryList());
//        System.out.println(categoryService.getCategoryList());
//        return "seller_item";//product管理页面
//
//    }
    @GetMapping("/showItem")
    public String ShowItem(Model model){
        return "seller_item";
    }
    @GetMapping("/Product1")
    public String ShowProduct(Model model){
        return  "seller_product";
    }
    @GetMapping("/Category")
    public String showCategory(Model model){
        return  "seller_category";
    }


    @ResponseBody
    @GetMapping("/items")/*test ok*/
    public CommonResponse<Map<HashMap<String, Object>, Integer>> itemManager(Model model){
        List<Item> itemList = itemService.getItemList().getData();
        HashMap<HashMap<String, Object>, Integer> salesitemMap = itemService.addQuantityToItems(itemList).getData();
        model.addAttribute("itemList",salesitemMap);
//        System.out.println(salesitemMap);
        return CommonResponse.creatForSuccess(salesitemMap);
    }






    @ResponseBody
    @PostMapping("/itemsEditor")/*test ok*/
    public CommonResponse itemEditor(@RequestParam("listprice") String listprice,@RequestParam("attr1") String attr1,@RequestParam("qty") String qty,@RequestParam("isup") String isup,@RequestParam("itemid") String itemid, Model model){
        System.out.println("1111");
        System.out.println(itemid);

        Item item = (Item)itemService.getItemByItemid(itemid).getData();

        item.setListprice(Double.parseDouble(listprice));
        item.setQty(Integer.parseInt(qty));
        item.setAttr1(attr1);
        item.setIsup(Boolean.parseBoolean(isup));

        return itemService.updateItemByItemId(itemid,item);
    }




    @GetMapping("/user")/*test ok*/
    public String userManager(Model model) {
        model.addAttribute("userList",userInfoService.getUserInfoList());
        System.out.println(userService.getUserList());
        return "seller_user";//用户管理界面
    }
    @GetMapping("/orders")/*test ok*/
    public String ordersManager(Model model) {
        model.addAttribute("orderList",orderService.getAllOrders());
        System.out.println(orderService.getAllOrders());
        return "seller_order";//订单管理界面
    }
    @GetMapping("/admin")/*test ok*/
    public String adminManager(Model model) {
        model.addAttribute("adminList",adminService.getAdminList());
//        System.out.println(adminService.getAdminList());
        System.out.println("管理员界面");
        return "seller_invite";//
    }
    @ResponseBody
    @PostMapping("/deleteAdmin")/*test ok*/
    public CommonResponse deleteAdmin(@RequestBody String jsonData) {
        try {
            // 解析 JSON 字符串
            JsonNode jsonNode = objectMapper.readTree(jsonData);
            System.out.println(jsonNode);
            String adminId = jsonNode.get("adminId").asText();
            System.out.println(adminId);
            return adminService.deleteAdminById(adminId);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.creatForError();
        }


    }
    @ResponseBody
    @GetMapping("/getInviteCode")/*test ok*/
    public CommonResponse getInviteCode(Model model) {
         String code = codeService.createInviteCode().getData();
         model.addAttribute("inviteCode",code);
        return codeService.createInviteCode();
    }
    @ResponseBody/*test ok*/
    @PostMapping("/user/resetPassword")
    public CommonResponse resetPassword(@RequestBody String jsonData) {
        try {
            // 解析 JSON 字符串
            JsonNode jsonNode = objectMapper.readTree(jsonData);
            // 提取 userId 和 password
            String userId = jsonNode.get("userId").asText();
            String password = jsonNode.get("password").asText();
            System.out.println("userid=" + userId);
            return userService.resetPasswordByUserId(userId,password);

        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.creatForError();
        }

    }
    @GetMapping("/login")
    public String Login() {
        return "seller_loginbyname";
    }
    @GetMapping("/login2")
    public String LoginByPhone() {
        return "seller_loginbyphone";
    }
    @GetMapping("/signOut")
    public String signOut(HttpSession session) {
        System.out.println("sj");
        session.removeAttribute("loginAdmin");
        return "redirect:http://localhost:8081/admin/login";
    }





    public double getOrderTotalPrice(List<Order> orders) {
        double total = 0;
        for (Order order : orders) {
            total += order.getTotalprice();
        }
        return total;
    }
    public Map<String, Double> calculateIncomeByYearMonth() {
        Map<String, List<Order>> ordersByYearMonth = orderService.groupPaidOrdersByYearAndMonth();
        Map<String, Double> incomeByYearMonth = new TreeMap<>();

        // 将已有数据放入 incomeByYearMonth
        for (Map.Entry<String, List<Order>> entry : ordersByYearMonth.entrySet()) {
            String yearMonth = entry.getKey();
            List<Order> orders = entry.getValue();
            double totalIncome = getOrderTotalPrice(orders);
            incomeByYearMonth.put(yearMonth, totalIncome);
        }

        // 补充缺失的年月并设置总收入为 0
        if (!incomeByYearMonth.isEmpty()) {
            String firstKey = incomeByYearMonth.keySet().iterator().next();
            String lastKey = incomeByYearMonth.keySet().iterator().next();

            String currentDate = firstKey;
            while (!currentDate.equals(lastKey)) {
                YearMonth currentYearMonth = parseYearMonth(currentDate);
                incomeByYearMonth.putIfAbsent(currentDate, 0.0);
                currentYearMonth = currentYearMonth.plusMonths(1);
                currentDate = formatYearMonth(currentYearMonth);
            }
        }

        // 补充前面缺失的年月
        YearMonth minYearMonth = parseYearMonth(incomeByYearMonth.keySet().iterator().next());
        YearMonth maxYearMonth = parseYearMonth(incomeByYearMonth.keySet().iterator().next());

        for (String key : incomeByYearMonth.keySet()) {
            YearMonth currentYearMonth = parseYearMonth(key);
            if (currentYearMonth.isBefore(minYearMonth)) {
                minYearMonth = currentYearMonth;
            }
            if (currentYearMonth.isAfter(maxYearMonth)) {
                maxYearMonth = currentYearMonth;
            }
        }

        YearMonth currentYearMonth = minYearMonth;
        while (!currentYearMonth.isAfter(maxYearMonth)) {
            String yearMonthStr = formatYearMonth(currentYearMonth);
            incomeByYearMonth.putIfAbsent(yearMonthStr, 0.0);
            currentYearMonth = currentYearMonth.plusMonths(1);
        }

        return incomeByYearMonth;
    }


    // 解析年月字符串为 YearMonth 对象
    private YearMonth parseYearMonth(String yearMonth) {
        String[] parts = yearMonth.split("-");
        int year = Integer.parseInt(parts[0]);
        int month = Integer.parseInt(parts[1]);
        return YearMonth.of(year, month);
    }

    // 格式化 YearMonth 对象为年月字符串
    private String formatYearMonth(YearMonth yearMonth) {
        return String.format("%d-%02d", yearMonth.getYear(), yearMonth.getMonthValue());
    }
}
